package org.aristotle.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.aristotle.common.utils.AristotleBeanUtils;
import org.aristotle.demo.model.entity.Favorite;
import org.aristotle.demo.model.entity.User;
import org.aristotle.demo.mapper.UserMapper;
import org.aristotle.demo.service.IBookService;
import org.aristotle.demo.service.IFavoriteService;
import org.aristotle.demo.service.IUserService;
import org.aristotle.demo.model.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IFavoriteService favoriteService;

    @Override
    public Page<UserVO> queryPageList(Long id, String username,String sex,Integer role,Integer current, Integer size) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();

        if (id != null) {
            queryWrapper.eq("id",id);
        }

        if (!StringUtils.isBlank(username)) {
            queryWrapper.like("username",username);
        }

        if (!StringUtils.isBlank(sex)) {
            queryWrapper.like("sex",sex);
        }

        if (role != null) {
            queryWrapper.eq("role",role);
        }

        Page<User> page = this.page(new Page<User>(current,size), queryWrapper);

        // 转为VO
        Page<UserVO> result = AristotleBeanUtils.transitionBean(page, Page<UserVO>::new);
        result.setRecords(AristotleBeanUtils.copyListProperties(page.getRecords(),UserVO::new));
        return result;
    }

    @Override
    public UserVO getById(Long id) {
        User user = this.baseMapper.selectById(id);

        UserVO userVO = AristotleBeanUtils.transitionBean(user, UserVO::new);

        return userVO;
    }

    @Override
    @Transactional
    public Boolean removeById(Long id) {
        /*删除中间表 Favorite*/
        QueryWrapper<Favorite> queryWrapperFavorite = new QueryWrapper<>();
        queryWrapperFavorite.eq("user_id",id);

        return super.removeById(id) && favoriteService.remove(queryWrapperFavorite);
    }
}
